<template>
  <div id="addPicturePage">
    <!--    标题-->
    <h2>
      {{ route.query?.id ? '编辑图片信息' : '上传图片信息' }}
    </h2>
    <a-typography-paragraph v-if="spaceId" type="secondary">
      保存至私有空间：<a :href="`/space/${spaceId}`">{{ spaceId }} </a>
    </a-typography-paragraph>
    <!-- 选择上传方式 -->
    <a-tabs v-model:activeKey="uploadType"
      >>
      <a-tab-pane key="file" tab="文件上传">
        <!--    上传组件-->
        <PictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
      </a-tab-pane>
      <a-tab-pane key="url" tab="URL 上传" force-render>
        <UrlPictureUpload :picture="picture" :spaceId="spaceId" :onSuccess="onSuccess" />
      </a-tab-pane>
    </a-tabs>

    <!--    编辑表单-->
    <a-form
      name="pictureForm"
      v-if="picture"
      layout="vertical"
      :model="pictureForm"
      @finish="handleSubmit"
    >
      <a-form-item name="name" label="图片名称">
        <a-input v-model:value="pictureForm.name" placeholder="请输入图片名称" />
      </a-form-item>
      <a-form-item name="introduction" label="图片简介">
        <a-textarea
          v-model:value="pictureForm.introduction"
          placeholder="请输入图片简介"
          :auto-size="{ minRows: 2, maxRows: 5 }"
        />
      </a-form-item>
      <a-form-item name="category" label="分类">
        <a-auto-complete
          :options="categoryOptions"
          v-model:value="pictureForm.category"
          placeholder="请输入分类"
          allowClear
        />
      </a-form-item>
      <a-form-item name="tags" label="标签">
        <a-select
          :options="tagOptions"
          v-model:value="pictureForm.tags"
          mode="tags"
          placeholder="请输入标签"
          allowClear
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">
          {{ route.query?.id ? '编辑图片信息' : '上传图片信息' }}
        </a-button>
      </a-form-item>
      <div v-if="picture" class="edit-bar">
        <a-space size="middle">
          <a-button :icon="h(EditOutlined)" @click="doEditPicture">裁剪图片</a-button>
          <a-button type="primary" ghost :icon="h(FullscreenOutlined)" @click="doImagePainting">
            AI 扩图
          </a-button>
        </a-space>
        <ImageCropper
          ref="imageCropperRef"
          :imageUrl="picture?.url"
          :picture="picture"
          :spaceId="spaceId"
          :onSuccess="onSuccess"
        />
        <TaskPainting
          ref="imageOutPaintingRef"
          :picture="picture"
          :spaceId="spaceId"
          :onSuccess="onImageOutPaintingSuccess"
        />

        />
      </div>
    </a-form>
  </div>
</template>
<script setup lang="ts">
import { computed, h, onMounted, reactive, ref } from 'vue'
import PictureUpload from '@/components/PictureUpload.vue'
import { useRoute } from 'vue-router'
import { EditOutlined, FullscreenOutlined } from '@ant-design/icons-vue'
import {
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import router from '@/router'
import UrlPictureUpload from '@/components/UrlPictureUpload.vue'
import ImageCropper from '@/components/ImageCropper.vue'
import TaskPainting from '@/components/TaskPainting.vue'

//参数定义
const picture = ref<API.PictureVO>()
const pictureForm = reactive<API.PictureEditRequest>({})
const categoryOptions = ref<String[]>([])
const tagOptions = ref<String[]>([])
const uploadType = ref<'file' | 'url'>('file')

//获取上传图片信息
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
}
//空间id
const spaceId = computed(() => {
  return route.query?.spaceId
})
//获取分类和标签选项
const getTagCateGoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  try {
    if (res.data.code === 0 && res.data.data) {
      //原数据为json，需要转换为下拉式接受格式 value  label
      tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
        return {
          value: data,
          label: data,
        }
      })
      categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
        return {
          value: data,
          label: data,
        }
      })
    } else {
      message.error('加载选项失败：' + res.data.message)
    }
  } catch (e) {
    message.error('加载选项失败：' + e)
  }
} // 图片编辑弹窗引用
const imageCropperRef = ref()
// AI 扩图弹窗引用
const imageOutPaintingRef = ref()

// AI 扩图
const doImagePainting = () => {
  if (imageOutPaintingRef.value) {
    imageOutPaintingRef.value.openModal()
  }
}

// 编辑成功事件
const onImageOutPaintingSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

// 编辑图片
const doEditPicture = () => {
  if (imageCropperRef.value) {
    imageCropperRef.value.openModal()
  }
}

// 编辑成功事件
const onCropSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

/**
 * 提交表单
 * @param values
 */
const handleSubmit = async (values: any) => {
  try {
    const pictureId = picture.value.id
    const res = await editPictureUsingPost({
      id: pictureId,
      spaceId: spaceId.value,
      ...values,
    })
    if (res.data.code == 0 && res.data.data) {
      message.success('创建成功')
      await router.push({
        path: `/picture/${pictureId}`,
      })
    } else {
      message.error('创建失败：' + res.data.message)
    }
  } catch (e) {
    message.error('创建失败：' + e)
  }
}
//加载
onMounted(() => {
  getTagCateGoryOptions()
})
// 获取老数据
const route = useRoute()
const getOldPicture = async () => {
  try {
    // 获取数据
    const id = route.query?.id
    if (id) {
      const res = await getPictureVoByIdUsingGet({
        id: id,
      })
      if (res.data.code === 0 && res.data.data) {
        const data = res.data.data
        picture.value = data
        pictureForm.name = data.name
        pictureForm.introduction = data.introduction
        pictureForm.category = data.category
        pictureForm.tags = data.tags
      }
    }
  } catch (e) {
    message.error('请联系管理员！')
  }
}
onMounted(() => {
  getOldPicture()
})
</script>
<style scoped>
#addPicturePage {
  max-width: 720px;
  margin: 0 auto;
}

#addPicturePage .edit-bar {
  text-align: center;
  margin: 16px 0;
}
</style>
